/**
 * 笔记编辑器页面组件
 * Note Editor Page Component
 */

class NoteEditor {
  constructor() {
    this.noteId = null;
    this.noteData = null;
    this.richEditor = null;
    this.isAutoSaveEnabled = true;
    this.hasUnsavedChanges = false;
    this.lastSaveTime = null;
    
    this.init();
  }

  /**
   * 初始化编辑器
   */
  init() {
    this.parseUrlParams();
    this.initializeRichEditor();
    this.bindEvents();
    this.loadNote();
    this.setupAutoSave();
    this.setupBeforeUnload();
  }

  /**
   * 解析URL参数
   */
  parseUrlParams() {
    const urlParams = new URLSearchParams(window.location.search);
    this.noteId = urlParams.get('id');
  }

  /**
   * 初始化富文本编辑器
   */
  initializeRichEditor() {
    const container = document.getElementById('rich-editor-container');
    
    this.richEditor = new RichEditor(container, {
      placeholder: '开始记录您的想法...',
      autoSave: false, // 我们自己控制自动保存
      maxLength: 50000,
      toolbar: [
        'bold', 'italic', 'underline', 'strikethrough', '|',
        'h1', 'h2', 'h3', '|',
        'ul', 'ol', '|',
        'link', 'image', 'video', 'audio', 'handwriting', 'emoji'
      ],
      onContentChange: (data) => {
        this.handleContentChange(data);
      },
      onSave: (data) => {
        return this.saveNote();
      }
    });
  }

  /**
   * 绑定事件
   */
  bindEvents() {
    // 返回按钮
    document.getElementById('back-btn').addEventListener('click', () => {
      this.handleBack();
    });

    // 保存按钮
    document.getElementById('save-btn').addEventListener('click', () => {
      this.saveNote();
    });

    // 预览按钮
    document.getElementById('preview-btn').addEventListener('click', () => {
      this.showPreview();
    });

    // 标题输入
    const titleInput = document.getElementById('note-title');
    titleInput.addEventListener('input', () => {
      this.handleTitleChange();
    });

    // 自动保存开关
    document.getElementById('auto-save-toggle').addEventListener('change', (e) => {
      this.isAutoSaveEnabled = e.target.checked;
      this.updateSaveStatus();
    });

    // 快捷操作
    document.getElementById('insert-date-btn').addEventListener('click', () => {
      this.insertCurrentDate();
    });

    document.getElementById('insert-time-btn').addEventListener('click', () => {
      this.insertCurrentTime();
    });

    document.getElementById('word-count-btn').addEventListener('click', () => {
      this.showWordCount();
    });

    // 预览模态框
    document.getElementById('close-preview-btn').addEventListener('click', () => {
      this.hidePreview();
    });

    document.getElementById('close-preview-btn-2').addEventListener('click', () => {
      this.hidePreview();
    });

    document.getElementById('export-btn').addEventListener('click', () => {
      this.exportNote();
    });

    // 字数统计模态框
    document.getElementById('close-word-count-btn').addEventListener('click', () => {
      this.hideWordCount();
    });

    document.getElementById('close-word-count-btn-2').addEventListener('click', () => {
      this.hideWordCount();
    });

    // 键盘快捷键
    document.addEventListener('keydown', (e) => {
      this.handleKeyboardShortcuts(e);
    });
  }

  /**
   * 加载笔记
   */
  async loadNote() {
    if (!this.noteId) {
      // 新建笔记
      this.noteData = {
        id: null,
        title: '',
        content: '',
        created_at: new Date().toISOString(),
        updated_at: new Date().toISOString()
      };
      this.updateNoteInfo();
      return;
    }

    try {
      this.showLoading();
      
      const response = await api.get(`/notes/${this.noteId}`);
      this.noteData = response.note;
      
      // 设置标题和内容
      document.getElementById('note-title').value = this.noteData.title || '';
      this.richEditor.setContent(this.noteData.content || '');
      
      this.updateNoteInfo();
      this.updateTitleCharCount();
      
    } catch (error) {
      console.error('加载笔记失败:', error);
      notification.error('加载笔记失败');
    } finally {
      this.hideLoading();
    }
  }

  /**
   * 保存笔记
   */
  async saveNote() {
    try {
      this.updateSaveStatus('saving');
      
      const title = document.getElementById('note-title').value.trim();
      const content = this.richEditor.getContent();
      
      if (!title && !content) {
        notification.warning('请输入标题或内容');
        return false;
      }

      const noteData = {
        title: title || '无标题',
        content: content
      };

      let response;
      if (this.noteId) {
        // 更新现有笔记
        response = await api.put(`/notes/${this.noteId}`, noteData);
      } else {
        // 创建新笔记
        response = await api.post('/notes', noteData);
        this.noteId = response.note.id;
        
        // 更新URL
        const newUrl = `${window.location.pathname}?id=${this.noteId}`;
        window.history.replaceState({}, '', newUrl);
      }

      this.noteData = response.note;
      this.hasUnsavedChanges = false;
      this.lastSaveTime = new Date();
      
      this.updateNoteInfo();
      this.updateSaveStatus('saved');
      
      notification.success('保存成功');
      return true;
      
    } catch (error) {
      console.error('保存笔记失败:', error);
      this.updateSaveStatus('error');
      notification.error('保存失败');
      return false;
    }
  }

  /**
   * 处理内容变化
   */
  handleContentChange(data) {
    this.hasUnsavedChanges = true;
    this.updateSaveStatus('unsaved');
    
    // 如果启用自动保存，重置定时器
    if (this.isAutoSaveEnabled) {
      this.resetAutoSave();
    }
  }

  /**
   * 处理标题变化
   */
  handleTitleChange() {
    this.hasUnsavedChanges = true;
    this.updateSaveStatus('unsaved');
    this.updateTitleCharCount();
    
    if (this.isAutoSaveEnabled) {
      this.resetAutoSave();
    }
  }

  /**
   * 更新标题字符计数
   */
  updateTitleCharCount() {
    const titleInput = document.getElementById('note-title');
    const charCount = titleInput.value.length;
    const charCountEl = document.getElementById('title-char-count');
    
    charCountEl.textContent = charCount;
    
    if (charCount > 180) {
      charCountEl.classList.add('text-red-500');
    } else {
      charCountEl.classList.remove('text-red-500');
    }
  }

  /**
   * 更新笔记信息显示
   */
  updateNoteInfo() {
    if (!this.noteData) return;
    
    const createdEl = document.getElementById('note-created');
    const updatedEl = document.getElementById('note-updated');
    
    createdEl.textContent = `创建时间: ${this.formatDate(this.noteData.created_at)}`;
    updatedEl.textContent = `更新时间: ${this.formatDate(this.noteData.updated_at)}`;
  }

  /**
   * 更新保存状态
   */
  updateSaveStatus(status = 'saved') {
    const indicator = document.getElementById('save-indicator');
    const text = document.getElementById('save-text');
    
    switch (status) {
      case 'saving':
        indicator.className = 'fa fa-spinner fa-spin text-blue-500';
        text.textContent = '保存中...';
        break;
      case 'saved':
        indicator.className = 'fa fa-circle text-green-500';
        text.textContent = this.lastSaveTime ? 
          `已保存 ${this.formatTime(this.lastSaveTime)}` : '已保存';
        break;
      case 'unsaved':
        indicator.className = 'fa fa-circle text-orange-500';
        text.textContent = '有未保存的更改';
        break;
      case 'error':
        indicator.className = 'fa fa-circle text-red-500';
        text.textContent = '保存失败';
        break;
    }
  }

  /**
   * 设置自动保存
   */
  setupAutoSave() {
    this.autoSaveTimer = null;
  }

  /**
   * 重置自动保存定时器
   */
  resetAutoSave() {
    if (this.autoSaveTimer) {
      clearTimeout(this.autoSaveTimer);
    }
    
    if (this.isAutoSaveEnabled) {
      this.autoSaveTimer = setTimeout(() => {
        if (this.hasUnsavedChanges) {
          this.saveNote();
        }
      }, 3000); // 3秒后自动保存
    }
  }

  /**
   * 显示预览
   */
  showPreview() {
    const title = document.getElementById('note-title').value.trim() || '无标题';
    const content = this.richEditor.getContent();
    
    document.getElementById('preview-title').textContent = title;
    document.getElementById('preview-content').innerHTML = content;
    document.getElementById('preview-modal').classList.remove('hidden');
  }

  /**
   * 隐藏预览
   */
  hidePreview() {
    document.getElementById('preview-modal').classList.add('hidden');
  }

  /**
   * 显示字数统计
   */
  showWordCount() {
    const content = this.richEditor.getTextContent();
    const title = document.getElementById('note-title').value;
    const fullText = title + content;
    
    const charCount = fullText.length;
    const wordCount = this.countWords(fullText);
    const paragraphCount = this.countParagraphs(content);
    const readingTime = Math.ceil(wordCount / 200); // 假设每分钟200字
    
    document.getElementById('char-count-display').textContent = charCount;
    document.getElementById('word-count-display').textContent = wordCount;
    document.getElementById('paragraph-count-display').textContent = paragraphCount;
    document.getElementById('reading-time-display').textContent = readingTime;
    
    document.getElementById('word-count-modal').classList.remove('hidden');
  }

  /**
   * 隐藏字数统计
   */
  hideWordCount() {
    document.getElementById('word-count-modal').classList.add('hidden');
  }

  /**
   * 插入当前日期
   */
  insertCurrentDate() {
    const date = new Date().toLocaleDateString('zh-CN');
    this.richEditor.insertText(date);
  }

  /**
   * 插入当前时间
   */
  insertCurrentTime() {
    const time = new Date().toLocaleString('zh-CN');
    this.richEditor.insertText(time);
  }

  /**
   * 导出笔记
   */
  exportNote() {
    const title = document.getElementById('note-title').value.trim() || '无标题';
    const content = this.richEditor.getTextContent();
    
    const exportContent = `# ${title}\n\n${content}`;
    
    const blob = new Blob([exportContent], { type: 'text/plain;charset=utf-8' });
    const url = URL.createObjectURL(blob);
    
    const a = document.createElement('a');
    a.href = url;
    a.download = `${title}.txt`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    
    URL.revokeObjectURL(url);
    notification.success('导出成功');
  }

  /**
   * 处理返回
   */
  async handleBack() {
    if (this.hasUnsavedChanges) {
      const shouldSave = confirm('您有未保存的更改，是否保存后离开？');
      if (shouldSave) {
        const saved = await this.saveNote();
        if (!saved) return; // 保存失败，不离开
      }
    }
    
    // 返回到仪表盘
    window.location.href = '/';
  }

  /**
   * 处理键盘快捷键
   */
  handleKeyboardShortcuts(e) {
    if (e.ctrlKey || e.metaKey) {
      switch (e.key.toLowerCase()) {
        case 's':
          e.preventDefault();
          this.saveNote();
          break;
        case 'p':
          e.preventDefault();
          this.showPreview();
          break;
        case 'e':
          e.preventDefault();
          this.exportNote();
          break;
      }
    }
    
    // ESC 键关闭模态框
    if (e.key === 'Escape') {
      this.hidePreview();
      this.hideWordCount();
    }
  }

  /**
   * 设置页面离开前的警告
   */
  setupBeforeUnload() {
    window.addEventListener('beforeunload', (e) => {
      if (this.hasUnsavedChanges) {
        e.preventDefault();
        e.returnValue = '您有未保存的更改，确定要离开吗？';
        return e.returnValue;
      }
    });
  }

  /**
   * 显示加载状态
   */
  showLoading() {
    document.getElementById('loading').classList.remove('hidden');
  }

  /**
   * 隐藏加载状态
   */
  hideLoading() {
    document.getElementById('loading').classList.add('hidden');
  }

  /**
   * 格式化日期
   */
  formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN');
  }

  /**
   * 格式化时间
   */
  formatTime(date) {
    return date.toLocaleTimeString('zh-CN', { 
      hour: '2-digit', 
      minute: '2-digit' 
    });
  }

  /**
   * 统计字数
   */
  countWords(text) {
    // 中文按字符计算，英文按单词计算
    const chineseChars = (text.match(/[\u4e00-\u9fa5]/g) || []).length;
    const englishWords = (text.match(/[a-zA-Z]+/g) || []).length;
    return chineseChars + englishWords;
  }

  /**
   * 统计段落数
   */
  countParagraphs(text) {
    return text.split(/\n\s*\n/).filter(p => p.trim().length > 0).length;
  }

  /**
   * 销毁编辑器
   */
  destroy() {
    if (this.autoSaveTimer) {
      clearTimeout(this.autoSaveTimer);
    }
    
    if (this.richEditor) {
      this.richEditor.destroy();
    }
  }
}

// 初始化笔记编辑器
document.addEventListener('DOMContentLoaded', () => {
  // 检查用户认证
  if (!auth.isAuthenticated()) {
    window.location.href = '/';
    return;
  }
  
  window.noteEditor = new NoteEditor();
});